import { fetchPermission } from "../../api/index"
import router, { DynamicRoutes } from "../../router/index"
import dynamicRoutes from "../../router/dynamic-router"
import { recursionRouter, setDefaultRoute } from "../../utils/recursion-router"

export default {
    namespaced: true,
    state: {
        infoObj: {},
        infoRouter: [],
        infoRouterShow: true,
        //--------
        permissionList: null,
        sidebarMenu: [],// 导航菜单
        currentMenu: '', // 高亮
        layoutRouter: '',  // 当前路由
        //-------------------
        tenantId: '', //上参数
        isCollapse: false,
        recordRoutes: [],
    },
    getters: {},
    mutations: {
        INFO_OBJ(state, item) {
            state.infoObj = item
        },

        SET_PERMISSION(state, routes) {
            state.permissionList = routes;
        },
        CLEAR_PERMSSION(state) {
            state.permissionList = null;

        },
        SET_MENU(state, menu) {
            state.sidebarMenu = menu;
            console.log('菜单', menu)
        },
        CLEAR_MENU(state) {
            state.sidebarMenu = []
        },
        USER_PARAMETER(state, menu) {
            state.infoRouter = menu
        },
        //-----------
        FOR_ROUTER(state, routes) {
            state.layoutRouter = routes.name
            state.currentMenu = routes.name

            //--------------
            let str = routes.fullPath
            let char = "?";
            let isExist = str.includes(char);
            //---------------------------参数
           if(state.infoObj.isAdmin != 1) {
             state.infoRouterShow = state.infoRouter.includes(`${routes.name}` + '-fund')
           }


            //----------------------------
            let obj = {
                name: routes.meta.name,
                key: routes.name,
                fullPath: routes.fullPath,
            }

           //--------------------------判断空
            console.log('ssss', routes.name)

            if(routes.name == null) {
                return
            }


            if (!localStorage.getItem('tabAlwaysRouter')) {
                state.recordRoutes = [obj]
                localStorage.setItem('tabAlwaysRouter', JSON.stringify([obj]))
            } else {
                state.recordRoutes = uniqueArrayOfObjects(JSON.parse(localStorage.getItem('tabAlwaysRouter')))
                        console.log('出发',  state.recordRoutes)

                let routerShow = false

                state.recordRoutes.forEach((item, index) => {
                    if (item.key == obj.key) {
                        routerShow = true
                    }
                })



                if (routerShow == false) {
                    state.recordRoutes.push(obj)

                    if (isExist == false) { // 表示当前有参数
                        localStorage.setItem('tabAlwaysRouter', JSON.stringify(state.recordRoutes))
                    }
                }

            }

            function uniqueArrayOfObjects(array) {
                // 将对象转换为字符串，并使用Set去重
                const unique = Array.from(new Set(array.map(item => JSON.stringify(item)))).map(item => JSON.parse(item));
                return unique;
            }

            function hasDuplicateField(array, field) {
                const uniqueValues = new Set();
                for (const obj of array) {
                    if (uniqueValues.has(obj[field])) {
                        return true;
                    }
                    uniqueValues.add(obj[field]);
                }
                return false;
            }
        },
        DE_WEIGHT(state, array) {
            array.forEach(item => {
                if (Array.children(item)) {
                    flattenArray(item); // 递归调用
                } else {
                    oneDimensionalArray.push(item); // 将非数组元素推入结果数组
                }
            });
        },
        //------------
        COLLAPSE_IS(state, show) {
            state.isCollapse = show
        }
    },
    // 异步访问
    actions: {
        async FETCH_PERMISSION({ commit, state }) {
            console.log('一步请求接口番薯',)
            //- ----获取用户是超级管理员判断
            let info = JSON.parse(localStorage.getItem('info'))
            commit('INFO_OBJ', info)

            // console.log('基本信息', info)

            if (info.isAdmin == 1) {
                console.log('获取到所有的权限', dynamicRoutes)
                let routes = dynamicRoutes

                let MainContainer = DynamicRoutes.find(v => v.path === "");

                let children = MainContainer.children;
                children.push(...routes)

                // 生成菜单
                commit("SET_MENU", children);
                // // 设置默认路由
                setDefaultRoute([MainContainer]);

                // 初始化路由
                let initialRoutes = router.options.routes;
                router.addRoutes(DynamicRoutes);
                commit("SET_PERMISSION", [...initialRoutes, ...DynamicRoutes])
            } else {
                let pathList = info.managerRoleResource.split(";");
                commit('USER_PARAMETER', pathList)
                // 示例路由配置数据
                const routes = dynamicRoutes;

                // 过滤函数：从多维路由配置中筛选特定路由
                function filterRoutes(routes, targetNames) {
                    return routes.reduce((acc, route) => {
                        // 如果当前路由的name在目标列表中，直接添加
                        if (targetNames.includes(route.name)) {
                            acc.push({ ...route });
                            return acc;
                        }

                        // 如果有子路由，递归处理
                        if (route.children && route.children.length > 0) {
                            const filteredChildren = filterRoutes(route.children, targetNames);
                            if (filteredChildren.length > 0) {
                                // 创建一个新对象，保留父路由的基本信息和过滤后的子路由
                                acc.push({
                                    ...route,
                                    children: filteredChildren,
                                });
                            }
                        }

                        return acc;
                    }, []);
                }

                // 获取到用户权限
                const filteredRoutes = filterRoutes(routes, pathList);

                // 打印过滤结果
                let MainContainer = DynamicRoutes.find(v => v.path === "");

                let children = MainContainer.children;
                children.push(...filteredRoutes)

                // 生成菜单
                commit("SET_MENU", children);
                // 设置默认路由
                setDefaultRoute([MainContainer]);

                // 初始化路由
                let initialRoutes = router.options.routes;
                router.addRoutes(DynamicRoutes);
                commit("SET_PERMISSION", [...initialRoutes, ...DynamicRoutes])

            }
        }
    }
}